(function ($) {
    $.fn.yqTextTable = function (opts, param) {
        if (typeof opts == 'string') {
            return $.fn.yqTextTable.methods[opts](this, param);
        }

        return this.each(function () {
            $this = $(this);
            var opt;
            if ($this.data("yqtype") == "yqTextTable") {
                opt = $.extend({}, options($this), opts);
            }
            else {
                opt = $.extend({}, $.fn.yqTextTable.defaults, opts);
                var $uniqueID = $this.attr("ID");
                if ($uniqueID === undefined) {
                    $uniqueID = $.getUniqueID();
                    $this.attr("ID", $uniqueID);
                }
            }

            if (opt.width === undefined && $this.width() > 0) {
                opt.width = $this.width();
            }
            else if (typeof opt.width != "undefined") {
                $this.width(opt.width);
            }

            //转换编辑尺寸
            if (typeof opt.editModeW == "string") {
                var r_str = opt.editModeW.substring(opt.editModeW.length - 1, opt.editModeW.length);
                if (r_str == "%") {
                    var wSacle = parseInt(opt.editModeW.substring(0, opt.editModeW.length - 1));
                    opt.editModeW = parseInt(wSacle * $(window).width() / 100);
                } else {
                    opt.editModeW = parseInt(opt.editModeW);
                }
            }
            if (typeof opt.editModeH == "string") {
                var r_str = opt.editModeH.substring(opt.editModeH.length - 1, opt.editModeH.length);
                if (r_str == "%") {
                    var wSacle = parseInt(opt.editModeH.substring(0, opt.editModeH.length - 1));
                    opt.editModeH = parseInt(wSacle * $(window).height() / 100);
                } else {
                    opt.editModeH = parseInt(opt.editModeH);
                }
            }

            //变量信息
            $this.data("texttable_opt", opt);
            $this.data("yqtype", "yqTextTable");

            init_text_before($this);
        });
    };

    $.fn.yqTextTable.defaults = {
        ajaxUrl: "/_db.html",
        titles: [],  //数据列配置对象
        rows: [],
        isEdit: true,
        isAdd: true,
        isDel: true,
        isMove: true,
        toexcel: false, //Excel导出
        excelName: "excel导出",   //Excel导出文件名
        inexcel: false, //Excel导入
        frozenNum: 0, //锁定列数量（锁定左侧）
        rownumbers: true,
        sumList: [],        //合计字段：a,b,c
        editModeW: 800, //模态编辑器宽度 格式为 800（数字）
        editModeH: 600, //模态编辑器高度 格式为 600（数字）
        beforeBindingTitle: function (titles, callback) {
            callback(titles);
        }, //标题绑定前
        afterBindingTitle: function () { },   //标题绑定后
        
        beforeEditShow:function(run_opt){
            return run_opt;
        }, //弹出框显示前
        
        beforeAdd: function (rows, row, callback) {
            callback(row);
        },
        afterChange: function (rows) {

        },

    };

    $.fn.yqTextTable.methods = {
        options: function (jq) {
            return options($(jq[0]));
        },
        destroy: function (jq) {
            destroy($(jq[0]));
        },
        resize: function (jq, width) {
            resize($(jq[0]), width);
        },
        clear: function (jq, data) {
            var opt = options($(jq[0]));
            opt.afterChange.call($(jq[0]), rows);
            setRows($(jq[0]), []);
        },
        setRows: function (jq, rows) {
            setRows($(jq[0]), rows);
        },
        getRows: function (jq) {
            return getRows($(jq[0]));
        },
        isEdit: function (jq, tf) {
            isEdit($(jq[0]), tf);
        }
    };

    function options($object) {
        return $object.data("texttable_opt");
    }

    function destroy($object) {
        $object.textbox("destroy");
    }

    function resize($object, width) {
        $object.textbox("resize", width);
    }

    function init_text_before($object) {
        var opt = options($object);
        opt.beforeBindingTitle.call($object, opt.titles,
            function (titles) {
                opt.titles = titles;
                init_text($object);
            });
    }

    function init_text($object) {
        var opt = options($object);

        var text_opt = {
            editable: false,
            iconAlign: 'right',
            icons: [{
                iconCls: 'yqwin-combo-btn-icon fa fa-pencil',
                handler: function (e) {
                    var pp = $object.textbox("textbox");
                    prevent_e = $.getPreventDefault(pp[0]);
                    prevent_e.id = $object.attr("id");
                    prevent_e.options = opt;

                    var mdiinfo = $.yqGetWindParams();

                    var run_opt = {
                        ajaxUrl: opt.ajaxUrl,
                        mdiinfo: mdiinfo,
                        prevent_e: prevent_e,
                        width: opt.editModeW,
                        height: opt.editModeH,
                        titles: opt.titles,
                        rows: opt.rows,
                        isEdit: opt.isEdit,
                        isAdd: opt.isAdd,
                        isDel: opt.isDel,
                        isMove: opt.isMove,
                        toexcel: opt.toexcel,
                        excelName: opt.excelName,
                        inexcel: opt.inexcel,
                        frozenNum: opt.frozenNum, //锁定列数量（锁定左侧）
                        rownumbers: opt.rownumbers,
                        sumList: opt.sumList,        //合计字段：a,b,c
                        callback: function (rows) {
                            opt.rows = rows;
                            //嵌入到datagrid中，兼容处理（需要重新创建对象）
                            if (typeof opt.p_target != "undefined") {
                                var ed = $.yqTextEditor(opt.p_target, opt.p_field);
                                if (!(ed === null)) {
                                    $(ed.target).yqTextTable('setRows', rows);
                                    opt.afterChange.call($(ed.target), rows);
                                }
                            }
                            else {
                                $object.textbox("setText", JSON.stringify(rows));
                                opt.afterChange.call($object, rows);
                            }
                        }
                    };

                    run_opt = opt.beforeEditShow.call($object, run_opt);

                    if (window.top == window.self) {
                        $.yqTableEditPopEdit(run_opt);
                    }
                    else {
                        window.top.$.yqTableEditPopEdit(run_opt);
                    }
                }
            }, {
                iconCls: 'yqwin-combo-btn-icon fa fa-times',
                handler: function (e) {
                    opt.afterChange.call($object, []);
                    setRows($object, []);
                }
            }]
        };

        $object.textbox(text_opt);

        setRows($object, opt.rows);
        isEdit($object, opt.isEdit);

        opt.afterBindingTitle.call($object);
    }

    function setRows($object, rows) {
        var opt = options($object);
        if (rows === undefined || rows == null || rows == "") {
            rows = [];
        }
        if (typeof rows === "string") {
            opt.rows = JSON.parse(rows);
        } else {
            opt.rows = rows;
        }

        setText($object);
    }

    function getRows($object) {
        var opt = options($object);
        if (opt.rows.length == 0) {
            return [];
        }
        else {
            return opt.rows;
        }
    }

    function setText($object) {
        var opt = options($object);
        if (opt.rows.length > 0) {
            $object.textbox("setText", JSON.stringify(opt.rows));
        }
        else {
            $object.textbox("setText", "");
        }
    }

    function isEdit($object, tf) {
        var opt = options($object);
        var icon0 = $object.textbox("getIcon", 0);
        var icon1 = $object.textbox("getIcon", 1);
        opt.isEdit = tf;
        if (opt.isEdit) {
            icon0.removeClass('icon-more');
            icon0.addClass('icon-edit');
            icon1.show();
            //icon1.removeClass('textbox-icon-disabled');
        } else {
            icon0.removeClass('icon-edit');
            icon0.addClass('icon-more');
            //icon1.addClass('textbox-icon-disabled');
            icon1.hide();
        }
    }
})(jQuery);
